package com.enzo.prms.common.util;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import java.util.UUID;

public class MailUtil {
    private static final Logger logger = Logger.getLogger(MailUtil.class);
    private static final String MAIL_PASSWORD = "mail.password";
    private static final String MAIL_USER_NAME = "mail.user.name";
    private static final String MAIL_HOST_NAME = "mail.host.name";
    private static final String MAIL_PORT = "mail.smtp.port";

    public static void init(Email email) {
        try {
            if (email != null) {
                email.setHostName(PropertiesUtil.getValue(MAIL_HOST_NAME));
                email.setSmtpPort(Integer.parseInt(PropertiesUtil.getValue(MAIL_PORT)));
                email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getValue(MAIL_USER_NAME), PropertiesUtil.getValue(MAIL_PASSWORD)));
                email.setSSLOnConnect(true);
                email.setFrom(PropertiesUtil.getValue(MAIL_USER_NAME));
            }
        } catch (EmailException e) {
            logger.error("MaiUtil:mail init failed:"+e.getMessage());
        }
    }

    public static void sendHtmlEmail(String subject, String msg, String to)throws Exception {
        HtmlEmail email=new HtmlEmail();
        init(email);
        email.setSubject(subject);
        email.addTo(to);
        email.setHtmlMsg(msg);
        email.setCharset("utf-8");
        // send the email
        email.send();
    }

    public static void sendActivateMail(String to, String link) {
        try {
            String subject = "激活帐号";
            StringBuffer sb = new StringBuffer();
            sb.append("<html><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
            sb.append("注册成功，点击下面链接激活帐号：<br/>");
            sb.append("<a href=\""+link+"\">"+link+"</a>");
            sb.append("</html>");
            sendHtmlEmail(subject, sb.toString(), to);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String subject="激活你的帐号";
        String to="enzocq@163.com";
        String msg="";
        sendHtmlEmail(subject, "111", to);
        System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));
    }

}
